<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-button type="primary" @click="showAddDialog('addFormRef')">添加角色</el-button>
            <el-table stripe
                      border
                      :header-cell-style="{textAlign: 'center'}"
                      :cell-style="{ textAlign: 'center' }"
                      :data="roleList"
                      row-key=""
            >
                <el-table-column type="expand" label=">">
                    <template slot-scope="scope">
                        <el-row v-for="(item1 , i1) in scope.row.children"
                                :class="['vcenter','bdbottom',i1 === 0 ? 'bdtop' : '']" :key="item1.id"
                        >
                            <el-col :span="5">
                                <el-tag type="primary" closable @close="removeRightById(scope.row,item1.id)">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="19">
                                <el-row v-for="(item2,i2) in item1.children"
                                        :class="['vcenter',i2 === 0 ? '' : 'bdtop']" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="danger" v-for="(item3,i3) in item2.children" closable
                                                @close="removeRightById(scope.row,item3,item2.children.length)"
                                                :key="item3.id">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete"
                                   @click="removeRoleById(scope.row.id)">删除
                        </el-button>
                        <el-button type="warning" size="mini" icon="el-icon-setting"
                                   @click="showRightsDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-dialog
                title="修改权限"
                :visible.sync="editDialogVisible"
                width="50%"
        >
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
                <el-form-item label="角色Id">
                    <el-input v-model="editForm.roleId" disabled></el-input>
                </el-form-item>
                <el-form-item prop="roleName" label="角色名称">
                    <el-input v-model="editForm.roleName"></el-input>
                </el-form-item>
                <el-form-item prop="roleDesc" label="角色描述">
                    <el-input v-model="editForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="edit">确 定</el-button>
  </span>
        </el-dialog>
        <el-dialog
                title="添加角色"
                :visible.sync="addDialogVisible"
                width="50%"
        >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
                <el-form-item prop="roleName" label="角色名称">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item prop="roleDesc" label="角色描述">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="add('addFormRef')">确 定</el-button>
  </span>
        </el-dialog>
        <el-dialog
                @close="selectedNode = []"
                title="分配权限"
                :visible.sync="rightsDialogVisible"
                width="50%"
        >
            <el-tree
                    :data="rightsTree"
                    :default-checked-keys="selectedNode"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    ref="treeRef"
                    highlight-current
                    :props="rightsProps">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                                <el-button @click="rightsDialogVisible = false">取 消</el-button>
                                <el-button type="primary" @click="editRights()">确 定</el-button>
                            </span>
        </el-dialog>
    </div>
</template>

<script>
  export default {
    name: "Roles",
    data() {
      return {
        roleList: [],
        roleId: 0,
        editDialogVisible: false,
        editForm: {},
        editFormRules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],
          roleDesc: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],

        },
        addDialogVisible: false,
        addForm: {
          roleName: '',
          roleDesc: ''
        },
        addFormRules: {
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],
          roleDesc: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],

        },
        rightsDialogVisible: false,
        rightsProps: {
          children: 'children',
          label: 'authName'
        },
        rightsTree: [],
        selectedNode: []
      }
    },
    created() {
      this.getRoleList();
      this.getRightsTree();
    },
    methods: {
      test() {
        alert("123");
      },
      async getRoleList() {
        const {data: res} = await this.$http({
          url: 'roles',
          method: 'get'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取角色列表数据失败');
        this.roleList = res.data;
      },
      async showEditDialog(id) {
        const {data: res} = await this.$http({
          url: 'roles/' + id,
          method: 'get'
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取角色信息失败');
        this.editForm = res.data;
        this.editDialogVisible = true;
      },
      async edit() {
        const {data: res} = await this.$http({
          url: 'roles/' + this.editForm.roleId,
          method: 'put',
          data: this.editForm
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('编辑角色失败');
        this.$message.success('编辑角色成功');
        this.getRoleList();
        this.editDialogVisible = false;
      },
      async removeRoleById(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        if (confirmResult === 'confirm') {
          const {data: res} = await this.$http({
            url: 'roles/' + id,
            method: 'delete'
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error('删除用户失败');
          this.getRoleList();
          return this.$message.success('删除用户成功');
        } else {
          this.$message.info('已取消删除');
        }
      },
      showAddDialog(formName) {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.addDialogVisible = true;
      },
      async add(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          const {data: res} = await this.$http({
            url: 'roles',
            method: 'post',
            data: this.addForm
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 201) return this.$message.error('添加角色失败');
          this.addDialogVisible = false;
          this.getRoleList();
          this.$message.success('添加角色成功');
        });
      },
      removeRightById: async function (role, item, length) {
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        if (confirmResult !== 'confirm') return this.$message.info('已取消删除');
        let rightId = item.id;
        let res1;
        if (length === 1) {
          let rightIds = item.pid.split(",");
          rightIds.push(rightId);
          for (let rightId of rightIds) {
            const {data: res} = await this.$http({
              url: `roles/${role.id}/rights/${rightId}`,
              method: 'delete'
            });
            res1 = res;
          }
        } else {
          const {data: res} = await this.$http({
            url: `roles/${role.id}/rights/${rightId}`,
            method: 'delete'
          });
          res1 = res;
        }
        if (res1.meta.status === 403) return this.$message.error(res1.meta.msg);
        if (res1.meta.status !== 200) return this.$message.error('删除失败');
        role.children = res1.data;
        this.$message.success('删除成功');
      },
      async getRightsTree() {
        const {data: res} = await this.$http({
          url: 'rights/tree',
          method: 'get',
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取权限数据失败');
        this.rightsTree = res.data;
      },
      showRightsDialog(row) {
        this.roleId = row.id;
        this.getSelectedNode(row);
        this.getRightsTree();
        this.rightsDialogVisible = true;
      },
      getSelectedNode(row) {
        if (row.children) {
          for (let child of row.children) {
            if (child.level === 2) {
              this.selectedNode.push(child.id);
            }
            this.getSelectedNode(child);
          }
        }
      },
      async editRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ];
        const idStr = keys.join(',');
        const {data: res} = await this.$http({
          url: `roles/${this.roleId}/rights`,
          method: 'post',
          data: {rids: idStr}
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('编辑权限失败');
        this.$message.success('修改用户权限成功');
        this.rightsDialogVisible = false;
        this.getRoleList();
      }
    }
  }
</script>

<style scoped>
    .el-breadcrumb {
        margin-bottom: 20px;
    }

    .el-table {
        margin-top: 20px;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }

    .el-tag {
        margin: 10px;
    }

    .bdtop {
        border-top: solid 1px #eeeeee;
    }

    .bdbottom {
        border-bottom: solid 1px #eeeeee;
    }
</style>